import { Injectable } from '@nestjs/common';
import { RoleEntity } from './entities/role.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Search } from 'src/common/decorators/search.decorator';

import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { ListRoleReturn } from './dto/list-role.dto';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(RoleEntity)
    private readonly roleRepository: Repository<RoleEntity>,
  ) {}

  async create(createRoleDto: CreateRoleDto): Promise<RoleEntity> {
    let roleItem = this.roleRepository.create(createRoleDto);
    roleItem = await this.roleRepository.save(roleItem);
    return await this.findOne(roleItem.id);
  }

  async findAll({
    page,
    limit,
    pagesize,
    offset,
    order,
    where,
  }: Search): Promise<ListRoleReturn> {
    const [rows, total] = await this.roleRepository.findAndCount({
      where,
      order,
      take: limit,
      skip: offset,
      select: ['id', 'roleName'],
    });

    return {
      total,
      rows,
      page,
      pagesize,
    };
  }

  async findOne(id: string): Promise<RoleEntity> {
    const roleItem = await this.roleRepository.findOne({
      relations: { permissions: true },
      where: { id },
      select: ['id', 'roleName'],
    });
    return roleItem;
  }

  async update(id: string, updateRoleDto: UpdateRoleDto): Promise<string> {
    await this.roleRepository.update(id, updateRoleDto);
    return 'success';
  }

  async remove(id: string): Promise<string> {
    await this.roleRepository.softDelete(id);
    return 'success';
  }
}
